<!-- SalesTrendChart.vue -->
<template>
    <div>
      <el-select v-model="timeType" @change="fetchData">
        <el-option label="最近一周" value="week" />
        <el-option label="最近一月" value="month" />
      </el-select>
      <div ref="chart" style="width: 100%; height: 400px;"></div>
    </div>
</template>
  
<script setup>
  import { ref, onMounted } from 'vue';
  import * as echarts from 'echarts';
  import { getSalesTrend } from '@/api/chart';
  
  const chart = ref(null);
  const timeType = ref('week');
  let chartInstance = null;
  
  const fetchData = async () => {
    try {
      const response = await getSalesTrend({ type: timeType.value });
      
      if (response.code === 1 && Array.isArray(response.data)) {
        const dates = response.data.map(item => item.date);
        const amounts = response.data.map(item => item.amount);
        
        const option = {
          title: {
            text: timeType.value === 'week' ? '最近一周销售额趋势' : '最近一月销售额趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>销售额: {c}元'
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: {
            type: 'value',
            name: '销售额(元)'
          },
          series: [{
            data: amounts,
            type: 'line',
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
                { offset: 1, color: 'rgba(58, 77, 233, 0.1)' }
              ])
            },
            itemStyle: {
              color: '#3a4de9'
            }
          }]
        };
        
        chartInstance.setOption(option);
      } else {
        console.error('获取数据失败: 数据格式不正确');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };
  
  onMounted(() => {
    chartInstance = echarts.init(chart.value);
    fetchData();
    
    window.addEventListener('resize', () => {
      chartInstance.resize();
    });
  });
</script>